/*
 * Segue Audio Player
 * Copyright 2011 Fraser McCrossan frasermccrossan@gmail.com
 * 
 * This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published
 *  by the Free Software Foundation, either version 3 of the License,
 *  or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.

 */

package com.frasermccrossan.segue;

import java.util.ArrayList;

import android.database.Cursor;
import android.provider.MediaStore.Audio.Media;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public abstract class BrowseTracks extends BrowseLibrary implements OnItemClickListener {

	public int lastAdded = -1;
		
	Track[] list_tracks;

	protected CharSequence[] trackArrayToStrings(Track[] tracks) {
		ArrayList<String> sl = new ArrayList<String>();
		sl.add(getString(R.string.all_tracks));
		for (Track t : tracks) {
			sl.add(t.toString());
		}
		return (CharSequence []) sl.toArray(new CharSequence[sl.size()]);
	}
	
	public void setListString(String selection, String[] selectionArgs) {
		Cursor tracks = cr.query(Media.EXTERNAL_CONTENT_URI,
				new String[] { Media._ID, Media.TITLE, Media.ARTIST, Media.ALBUM, Media.TRACK, Media.DURATION },
				selection, selectionArgs,
				Media.ALBUM+","+Media.TRACK+","+Media.TITLE);
		if (tracks == null) {
			list_strings = new String[0];
			proclaim(R.string.no_tracks);
			finish();
		}
		else {
			list_tracks = new Track[tracks.getCount()];
			for (tracks.moveToFirst(); !tracks.isAfterLast(); tracks.moveToNext()) {
				list_tracks[tracks.getPosition()] = new Track(tracks.getLong(0), tracks.getString(1),
															  tracks.getString(2), tracks.getString(3),
															  tracks.getInt(4), tracks.getInt(5));
			}
			tracks.close();
			list_strings = trackArrayToStrings(list_tracks);
		}

	}

	// override to do something different
	@Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
		if (position != lastAdded) { //avoid accidental double-taps
			if (position == 0) {
				// the "all tracks" entry
		    	proclaim(String.format(getString(R.string.adding_n_tracks), list_tracks.length));
				for (Track t : list_tracks) {
					mQueuePlayer.addTrack(t);
				}
			}
			else {
		    	proclaim(String.format(getString(R.string.adding_track), list_tracks[position-1].title));
				mQueuePlayer.addTrack(list_tracks[position-1]);
				lastAdded = position;
			}
		}
	}
}